package com.hb.ssmdemo.tools.udp;


import java.net.DatagramPacket;
import java.net.InetAddress;
import java.util.List;

import org.apache.log4j.Logger;

import com.hb.ssmdemo.tools.Configuration;

/**
 * 
 *@ClassName:SendData   
 *@Description:后台发送数据发送端
 *
 **/
public class SendData {
	
	public static Logger log = Logger.getLogger(SendData.class);
	//读取配置文件
    private static Configuration con;
    static {
    	//初始化
        con = Configuration.getInstance(); 
    }
    
    /**
     * 
     * UDP数据发送端
     * @param terCode 终端编号
     * @param cmd 发送命令
     * 
     */
    public static void udpSendData(String terCode,String cmd,boolean flag) throws Exception{
    	
    	//服务器接收端口
        int port = Integer.parseInt(con.getServerPort());
        //根据终端编号，找出相应的服务器IP地址
        List<Udpset> model = JDBCUtils.queryAllUdpsetInfo();
        if(model != null){
        	InetAddress ia = InetAddress.getByName(model.get(0).getServerip());
        	log.info("数据交换机：" + port + "下发给终端的字符串：" + cmd);
        	//16进制字符串转换为byte数组
        	byte[] buffer = DeCode.hexStringToByte(cmd);
        	//封装要发送数据
        	DatagramPacket sendData = new DatagramPacket(buffer, buffer.length, ia, port);
        	//根据端口号,找出相应的socket
        	if( ReceiveData.socketMap.get(Integer.parseInt(model.get(0).getLocalRPort())) != null){
        		//发送数据
        		ReceiveData.socketMap.get(Integer.parseInt(model.get(0).getLocalRPort())).send(sendData);
        	}
        }
    }
}
